package com.zhz.company.config.mybtatis;

import cn.hutool.system.OsInfo;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zhz.common.utils.IdWorker;
import com.zhz.company.config.mybtatis.plugin.InsertIgnorePlugin;
import com.zhz.company.config.mybtatis.type.StrippedBigDecimalTypeHandler;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * Mybatis 配置
 *
 * @author zhouhengzhe
 **/
@Configuration
public class MybatisPlusConfig  implements InitializingBean {
    @Autowired
    private MybatisPlusProperties mybatisPlusProperties;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
    /**
     * INSERT IGNORE 改写插件
     */
    @Bean
    public InsertIgnorePlugin insertIgnorePlugin() {
        return new InsertIgnorePlugin();
    }

    @Override
    public void afterPropertiesSet() {
        MybatisConfiguration configuration = mybatisPlusProperties.getConfiguration();
        // windows/mac 下默认开启 mybatis sql 日志打印
        OsInfo osInfo = new OsInfo();
        if (osInfo.isWindows() || osInfo.isMac()) {
            if (Objects.isNull(configuration.getLogImpl())) {
                mybatisPlusProperties.getConfiguration().setLogImpl(StdOutImpl.class);
            }
        }
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        typeHandlerRegistry.register(BigDecimal.class, new StrippedBigDecimalTypeHandler());
        typeHandlerRegistry.register(JdbcType.DECIMAL, new StrippedBigDecimalTypeHandler());
    }
    @Bean
    public IdWorker idWorker(){
        return new IdWorker();
    }


}
